package com.tiku.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tiku.common.ResultJson;
import com.tiku.entity.ChapterInfo;
import com.tiku.entity.UserPayTiku;
import com.tiku.entity.UserQuestionLog;
import com.tiku.service.ChapterInfoService;
import com.tiku.mapper.ChapterInfoMapper;
import com.tiku.service.UserPayTikuService;
import com.tiku.utils.RedisCache;
import com.tiku.utils.ThreadLocalUtil;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Objects;

/**
 *
 */
@Service
public class ChapterInfoServiceImpl extends ServiceImpl<ChapterInfoMapper, ChapterInfo>
    implements ChapterInfoService{


    @Autowired
    private ChapterInfoMapper chapterInfoMapper;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private UserPayTikuService userPayTikuService;

    @Override
    public ResultJson chapterList(String chapter,String specification) {
        String userId = ThreadLocalUtil.getThreadLocal();
        List<ChapterInfo> chapterInfos = chapterInfoMapper.selectList(new QueryWrapper<ChapterInfo>().select("DISTINCT * ").lambda().eq(ChapterInfo::getMenuId, chapter));
        //key : questionLog: + 用户id +类目ID+ 章节ID + 子章节ID + 题目ID
        Integer count=0;
        Boolean freeFlag=false;
        //获取用户购买的题库，如果当前请求的题库用户已经购买 则打开免费标识
        UserPayTiku tiku = userPayTikuService.getOne(new LambdaQueryWrapper<UserPayTiku>().eq(UserPayTiku::getUserId, userId)
                .eq(UserPayTiku::getPaySpecId,specification));
        if (!Objects.isNull(tiku)){
            freeFlag=true;
        }
        for (ChapterInfo chapterInfo : chapterInfos) {
            if (freeFlag){
                chapterInfo.setFreeFlag(0);
            }
            count=0;
            Collection<String> keys = redisCache.keys("questionLog:" + userId +specification+chapter+ chapterInfo.getId()+"*");
            chapterInfo.setQuestionQuantity(keys.size());
            for (String key : keys) {
                UserQuestionLog userQuestionLog = redisCache.getCacheObject(key);
                if (userQuestionLog.getRightflag()==0) {
                    count++;
                }
            }
            chapterInfo.setFailQuantity(count);

            System.out.println(keys);
        }



        return ResultJson.success(chapterInfos);


    }

}




